// pages/tasks/detail/detail.js
const app = getApp();
const regeneratorRuntime = app.globalData.regeneratorRuntime;
const taskService = require("../../../apiservice/task/taskservice");
const screenitemservice = require("../../../apiservice/screen/screenitemservice");
const util = require("../../../utils/util")
const detailbehavior = require("./detailbehavior");
const jsonData = require("./jsondata.js");

Component({
	behaviors: [detailbehavior],
	/**
	 * 页面的初始数据
	 */
	data: {
		selectTelResult: 100000000,
		selectTelText: "已联系",
		selectConnectResult: 100000000,
		selectConnectText: "形成预约",
		telResultIndex: 0,
		connectResultIndex: 0,
		description: "",
		taskDetail: {},
		telResult: jsonData.telResult,
		connectResult: jsonData.connectResult,
		delayResult: null,
		delayResultIndex: 0,
		delayResultId: 0,
		delayResultText: "",
		screencallbackid: '',

		//筛查通知
		screenNotice: {},
		//是否显示页面
		//正常任务 1
		//无电话号码的任务 2
		//筛查通知 3
		isShowPage: 1, //"正常任务"
    startReservationDate: util.addDateSeg(new Date().getTime(), "Month", 0, '-'),
    endReservationDate: util.addDateSeg(new Date().getTime(), "Month", 2, '-'),
    appointmenttothehospitaldate: util.frmatDate(new Date()),
    hospitalList:[],
    hospitalindex:'',
    officeArray:[],
    officeIndex:0,
    itemData: [{ "id": 0, "name": "请选择" },{ "id": 7, "name": "近视手术" }, { "id": 3, "name": "高度近视" }, { "id": 11, "name": "医学验光配镜" }, { "id": 2, "name": "儿童眼病" },
    { "id": 8, "name": "斜弱视" },
    { "id": 5, "name": "角膜塑形镜" },
    { "id": 1, "name": "白内障" },
    { "id": 9, "name": "眼底病" },
    { "id": 4, "name": "角膜及眼表" },
    { "id": 10, "name": "眼整形眼眶病" },
    { "id": 12, "name": "青光眼" },
    { "id": 6, "name": "泪道病" },
    { "id": 14, "name": "角膜移植" },
    { "id": 15, "name": "青光VIP特需门诊眼" },
    { "id": 13, "name": "其他" }
    ],
    itemindex:0
	},
	
	methods: {
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: async function(options) {
			wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
				title: '加载中',
				icon: 'loading'
			});
			try {
				
				var reqResult = await taskService.getTaskDetail(options.taskid);
				var taskInfo = reqResult.data;
				this.setData({
					taskDetail: taskInfo,
					description:taskInfo.description,
				});
				console.log(taskInfo);
				if (taskInfo.new_type == 100000001) {
					if (taskInfo.new_tel || taskInfo.new_mobile || taskInfo.address1_Telephone1) {
						await this.GetScreenCallBackData(taskInfo.taskId, taskInfo.new_screenId);
						this.setData({
							isShowPage: 1, //"正常任务",
						});
					} else {
						this.setData({
							isShowPage: 2, //"无电话号码的任务",
						});
					}
				} else if (taskInfo.new_type == 100000000) {
					this.setData({
						isShowPage: 3, //"筛查通知",
					});
					if (taskInfo.taskId) {
						var result = await taskService.GetScreenNoticeViewData(taskInfo.taskId);
						if (result != null) {
							console.log(result);
							this.setData({
								screenNotice: result.data
							});
						}
					}
				}
        this.GetAllHospital();
        
				console.log(this.data.isShowPage);
			} catch (e) {
				//TODO handle the exception
			} finally {
				wx.hideLoading();
			}
		},
    getPickerValue2: function (targetObj, targetObjName, id) {
      for (let index in targetObj) {
        if (targetObj[index][targetObjName] == id) {
          return index
        }
      }
    },
		changeTelResult: function(e) {
			var id = this.data.telResult[e.detail.value].id;
			var name = this.data.telResult[e.detail.value].name;
			//推迟回访
			this.delayCallBack(id);
			this.setData({
				selectTelResult: id,
				selectTelText: name,
				telResultIndex: e.detail.value
			});
			console.log(this.data.selectTelResult);
		},
		
		delayCallBack:function(telResultId){
			if (telResultId == 100000001 || telResultId == 100000002 ||
				telResultId == 100000003 || telResultId == 100000004 ||
				telResultId == 100000005) {
				this.setData({
					delayResult: jsonData.delayResult,
					delayResultIndex: 0,
					delayResultText: jsonData.delayResult[0].name,
					delayResultId: jsonData.delayResult[0].id,
				})
				console.log(this.data.delayResultText, this.data.delayResultId);
			} else {
				this.setData({
					delayResult: null,
					delayResultIndex: -1,
					delayResultText: -1,
					delayResultId: -1,
				})
			}
		},
		
		changeconnectResult: function(e) {
			var id = this.data.connectResult[e.detail.value].id;
			var name = this.data.connectResult[e.detail.value].name;
			this.setData({
				selectConnectResult: id,
				selectConnectText: name,
				connectResultIndex: e.detail.value
			});
			console.log(this.data.connectResult);
		},

    //预约日期
    dateChange: function (e) {
      //console.log(e);
      this.setData({
        appointmenttothehospitaldate: e.detail.value
      })
    },
    changeHospital: function (e) {
      var siteId = this.data.hospitalList[e.detail.value].siteId;
      this.setData({
        hospitalindex: e.detail.value
      });
      this.GetDepartmentsByHospID(siteId);

    },
    bindOfficeChange: function (e) {
      this.setData({
        officeIndex: e.detail.value
      });
    },
    //项目
    bindItemChange: function (e) {
      this.setData({
        itemindex: e.detail.value
      })
    },
		
		//推迟回访
		changedelayResult: function(e) {
			var id = this.data.delayResult[e.detail.value].id;
			var name = this.data.delayResult[e.detail.value].name;
			this.setData({
				delayResultId: id,
				delayResultIndex: e.detail.value,
				delayResultText: name
			});
			console.log(this.data.delayResultText, this.data.delayResultId);
		},
		
		changedescription: function(e) {
			var deail = e.deail;
			this.setData({
				description: e.detail
			});
			console.log(e.detail);
		},

    GetAllHospital:  function () {
      var that = this;
      var userinfo = app.globalData.userInfo;
      screenitemservice.GetAllHospital().then(function (success) {
        that.setData({
          hospitalList: success.data,
          hospitalindex: that.getPickerValue2(success.data, 'siteId', userinfo.siteid)
        });
        that.GetDepartmentsByHospID(userinfo.siteid);
      }).catch(function (ex) {
        console.log(ex);
      })
    },

    GetDepartmentsByHospID:  function (hospitalid) {
      var that = this;
      screenitemservice.GetDepartmentsByHospID(hospitalid).then(function (success) {  
        var result = success.data;
        if (result.length >= 1 && result[0].new_departmentId == undefined) {
          result = [];
        } else {
          // var officeIndex = that.data.officeIndex;
          // var new_department = result[officeIndex].new_departmentId
          // that.setData({
          //   ['reservation.new_department']: new_department
          // });
        }
        that.setData({
          officeArray: result
        });
        // if (this.data.officeArray.length > 0) {
        //   //console.log(this.data.officeArray);
        //   var officeIndex = this.data.officeIndex;
        //   var new_department = this.data.officeArray[officeIndex].new_departmentId
        //   this.setData({

        //   });
        // }
      }).catch(function (ex) {
        console.log(ex);
      })
    },
		
		onSave: function(e) {
			//debugger;
			var that = this;
			//"正常任务"
			if (this.data.isShowPage == 1) {
        if (this.data.selectConnectText == '形成预约' && this.data.selectTelText == '已联系'){
          if (this.data.itemindex == 0) {
            wx.showToast({
              title: '项目不能为空!',
              duration: 2000,
              icon: 'none'
            })
            return;
          }
        }
				if (this.data.screencallbackid) {
					if (that.data.delayResult) {
						that.delayCallBackResult()
					} else {
						that.updateCallBackResult();
					}
				} else {
					if (that.data.delayResult) {
						that.delayCallBackResult()
					} else {
						that.createCallBackResult();
					}
				}
			}
			//"无电话号码的任务"
			else if (this.data.isShowPage == 2) {
				wx.showModal({
					title: "提示",
					content: "你确定取消任务吗？",
					success: function(res) {
						if (res.confirm) {
							console.log("确定取消任务");
							that.cancelTask();
						} else {
							console.log("没有取消任务");
						}
					}
				})
			}
			//"筛查通知"
			else if (this.data.isShowPage == 3) {
				wx.showModal({
					title: "提示",
					content: "你确定完成任务吗？",
					success: function(res) {
						if (res.confirm) {
							console.log("确定完成任务");
							that.accomplishTask();
						} else {
							console.log("没有完成任务");
						}
					}
				})
			}
		},
		
		//取消任务
		cancelTask: function() {
			var taskId = this.data.taskDetail.taskId;
			var entityName = "task";
			var state = 2;
			var status = 6;
			taskService.UpdateState(taskId, entityName, state, status).then(function(result) {
				console.log(result);
				wx.switchTab({
					url: "../list/list",
					success: function(e) {
						var page = getCurrentPages().pop();
						if (!page) return;
						page.onLoad();
					}
				});
			}).catch(function(error) {
		
			})
		},
		
		//完成任务
		accomplishTask: function() {
			var taskId = this.data.taskDetail.taskId;
			var entityName = "task";
			var state = 1;
			var status = 5;
			taskService.UpdateState(taskId, entityName, state, status).then(function(result) {
				console.log(result);
				wx.switchTab({
					url: "../list/list",
					success: function(e) {
						var page = getCurrentPages().pop();
						if (!page) return;
						page.onLoad();
					}
				});
			}).catch(function(error) {})
		},
		

		callPhone: function(event) {
			console.log(event);
			if (this.data.taskDetail.new_mobile) {
				var phone = this.data.taskDetail.new_mobile;
				console.log(phone);
				wx.makePhoneCall({
					phoneNumber: phone,
				});
			}
		},
		
		callLandline: function(event) {
			console.log("滴滴");
			console.log(event);
			if (this.data.taskDetail.new_tel) {
				var phone = this.data.taskDetail.new_tel;
				console.log(phone);
				wx.makePhoneCall({
					phoneNumber: phone,
				});
			}
		},
		
		/*
		 *给picker赋值
		 * @param jsonDataName json静态数据配置对象名
		 * @param targetObj 目标对象
		 * @param targetObjName 目标对象名
		 * @param valueIndexName Picker Value绑定名
		 * @param textName Picker 显示名
		 * ****/
		getPickerValue: function(jsonDataName = '', targetObj = {}, targetObjName = '', valueIndexName = '', textName = '') {
			if (!targetObj.data[targetObjName]) return;
			for (let index in this.data[jsonDataName]) {
				//debugger;
				if (this.data[jsonDataName][index].id == targetObj.data[targetObjName]) {
					//debugger;
					this.setData({
						[valueIndexName]: index,
						[textName]: this.data[jsonDataName][index].name
					})
					break;
				}
			}
		},
		
		
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {
		
		},
		
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
		
		},
		
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {
		
		},
		
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
		
		},
		
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {
		
		},
		
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {
		
		},
		
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {
		
		}
	}

})
